package com.hllxd.hism.passport.login.gateway.dao.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Yarn的应用操作
 *
 * @author lixiyong
 * @date 2019-01-02 10:11
 */
@Slf4j
@Component("rockAssemApiMapper")
public class SmsVpcMapperImpl implements SmsVpcMapper {

//    private final static String URL_HOST = "175.25.18.221";
//    private final static Integer URL_PORT = 8087;
//    private final static String URL_URI = "/MWGate/wmgw.asmx/MongateCsSpSendSmsNew";
//    private final static String ACCESS_USER = "J71268";
//    private final static String ACCESS_PSWD = "223321";
//    public static final String ALARM_TOKEN = "df987c60fddfdf4304dfbf1816e1b078";

    public static final String ALARM_TOKEN = "8d3dca200ece48133c38ce329b81f9d6";


    public static boolean isOK(JSONObject obj) {
        String status = obj.getString("code");
        return (status != null && "000".equals(status));
    }

    /**
     * 发送短信
     */
    public static String sendMessage(String oaname, String content) {
        Map<String, String> pp = new HashMap<>();
        pp.put("Content-Type", "application/x-www-form-urlencoded");
        StringBuilder data = new StringBuilder();
        data.append("oaname=").append(oaname).append("&")
                .append("content=").append(content).append("&")
                .append("token=").append(ALARM_TOKEN);
        return HttpclientUtil.post("http://openmsg.monitor.op.58dns.org/channel/sms", data.toString(), pp);
    }
//    public static String sendMessage(String phone, String text) {
//        StringBuffer result = null;
//        try {
//            result = new StringBuffer();
//            result.append("userId=" + ACCESS_USER + "&");
//            result.append("password=" + ACCESS_PSWD + "&");
//            result.append("pszMobis=" + phone + "&");
//            result.append("pszMsg=" + new String(text.getBytes(), "UTF-8") + "&");
//            result.append("iMobiCount=" + 1);
//        } catch (UnsupportedEncodingException e) {
//            log.warn("UnsupportedEncodingException: {}.", e.toString());
//        }
//        return post("http", URL_HOST, URL_PORT, URL_URI, result.toString());
//    }

    public static String post(String type, String ip, int port, String uri, String param) {
        try {
            java.net.URL url = new URL(type, ip, port, uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置接收数据的格式
            connection.setRequestProperty("Accept", "text/plain");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.connect();
            // utf-8编码
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.append(param);
            out.flush();
            out.close();

            int code = connection.getResponseCode();
            InputStream is = null;
            if (code == 200) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
                log.info("code: {}", code);
            }
            // 读取响应
            // 获取长度
            int length = connection.getContentLength();
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                return new String(data, "UTF-8");
            }

        } catch (IOException e) {
            log.info("IOException: {}.", e.toString());
        }
        // 自定义错误信息
        return "error";
    }

    @Override
    public String sendSms(String oaAccount, String messageContent, String bizSrc, String sysCode) {
        log.info("send sms: {}, {}.", oaAccount, messageContent);
        // {"status": 6, "msg": "\u544a\u8b66\u7ec4lixiyong01\u4e0d\u5b58\u5728\uff01"}
        String ret = sendMessage(oaAccount, messageContent);
        JSONObject obj = JSON.parseObject(ret);
        Integer code = obj.getInteger("status");
        log.info("send result, code: {}, msg: {}.", code, obj.getString("msg"));
        if(code==0) {
            return "000";
        }
        return ret;
    }
}
